<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    .cvs{border: solid 1px black;}
  </style>
</head>
<body>
  <canvas class="cvs"></canvas>
  <input type="button" class="download" value="下载图片">
</body>
<script>

  // 1. 选中要导出成图片的canvas元素
  const cvs = document.querySelector(".cvs")
  cvs.width = 400;
  cvs.height = 400;
  const c2d = cvs.getContext("2d");

  let r = 100;
  let x = 200;
  let y = 200;
  clock(r, x, y);

  setInterval(()=>{
    c2d.clearRect(0, 0, cvs.width, cvs.height);
    c2d.beginPath();
    clock(r, x, y);
  }, 1000);

  function clock(r, x, y){
    c2d.arc(x, y, r, 0, 2*Math.PI);
    c2d.stroke();
    for(let i=0;i<60;i++){
      const leg = i%5===0 ? -10 : -5;
      line(c2d, -r, leg, 360 / 60 * i);
    }
    const d = new Date();
    const h = d.getHours();
    const m = d.getMinutes();
    const s = d.getSeconds();
    line(c2d, 10, 50, 360 / 12 * h + (360/12/60*m));
    line(c2d, 10, 65, 360 / 60 * m + (360/60/60*s));
    line(c2d, 10, 90, 360 / 60 * s);
    c2d.beginPath();
    c2d.arc(200, 200, 5, 0, 2*Math.PI);
    c2d.fill();
    c2d.textAlign = "center";
    c2d.textBaseline = "middle";
    c2d.font = "12px 黑体";
    c2d.fillText("劳力士", 200, 216);
    for(let i=-2;i<10;i++){
      c2d.font = "16px 黑体";
      let x = (r-20) * Math.cos(dth(360/12*i)) + 200;
      let y = (r-20) * Math.sin(dth(360/12*i)) + 200;
      c2d.fillText(i+3, x, y);
    }
  }
  function line(c2d, start, leg, deg){
    c2d.beginPath();
    c2d.save();
    c2d.translate(200, 200);
    c2d.rotate( dth(deg) );
    c2d.moveTo(0, start);
    c2d.lineTo(0, -leg + start);
    c2d.restore();
    c2d.stroke();
  }
  function dth(deg){
    return Math.PI / 180 * deg;
  }

  
  const download = document.querySelector(".download");
  download.onclick = function(){
    // 将canvas数据转成base64数据
    const base64 = cvs.toDataURL("image/png");
    // 将base64数据解码
    const strBase64 = atob( base64.split(",")[1] );
    // 创建utf-8原始数据（长度为base64解码后的字符长度）
    const utf_8 = new Uint8Array(strBase64.length);
    // 将base64解码后的数据转成Unicode编码后，存入utf-8数组
    for(let n=0;n<strBase64.length;n++){
      utf_8[n] = strBase64.charCodeAt(n)
    }
    // 根据utf-8数据，创建文件对象
    const file = new File([utf_8], "测试图片", {type:"image/png"});
    // 根据文件对象创建url字符
    const href = URL.createObjectURL(file);
    // 准备a标签，用于下载文件
    const a = document.createElement("a");
    a.href = href;
    a.download = "测试图片";
    document.body.appendChild(a);
    a.click();
    // 删除a标签
    a.remove();
    // 释放指向文件资源的url字符
    URL.revokeObjectURL(href);
  }



  
</script>
</html>